import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, Alert, TouchableOpacity, ScrollView, Text, Vibration } from 'react-native';
import { Icon, List, ListItem, Button, SideMenu, SearchBar } from 'react-native-elements';
import Loader from './widgets/Loader';
import RefreshScrollView from './widgets/RefreshScrollView';
import AssignFactoryButton from './components/AssignFactoryButton';
import { primaryColor, toast } from './utils';
import { Calendar } from 'react-native-calendars';
import { AssignFactoryQuery } from './graphql';
import moment from 'moment';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white'
  },
  button: {
    paddingTop: 32
  },
  bagNotFound: {
    color: 'red'
  },
  list: {
    marginTop: 0
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  header: {
    padding: 8
  },
  checked: {
    color: '#4CAF50'
  },
  selected: {
    color: primaryColor
  },
  orderNumber: {
    color: '#795548'
  },
  iconLeft: {
    marginLeft: 16
  },
  preview: {
    height: 50
  },
  business: {
    color: '#2196F3'
  }
});

class AssignFactoryPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    const { selectFactory, selects, date } = navigation.state.params||{};

    return {
      title: selectFactory?selectFactory.name:`Unassigned`,
      tabBarLabel: screenProps.chinese?`订单分厂`:`Assign Factory`,
      tabBarIcon: ({tintColor}) => <Icon name='local-shipping' color={tintColor} size={24}/>,
      headerRight: <AssignFactoryButton navigation={navigation} selects={selects}
        date={date||moment([moment().year(), moment().month(), moment().date()]).subtract(1,'days').toDate().toString()} onSuccess={()=>navigation.setParams({selects:[]})}/>
    };
  }
  state = {}
  onSelectDate = ({year, month, day, hour=0}, calendarOpen=false) => {
    const date = moment([year, month-1, day, hour]).toDate().toString();
    this.props.navigation.setParams({date});
    this.setState({isOpen: false});
  }
  onSelectBag = (bags) => {
    let selects = (this.props.navigation.state.params&&this.props.navigation.state.params.selects)||[];
    const select = bags.find(bag=>selects.indexOf(bag)>=0);
    if (select) {
      this.props.navigation.setParams({selects: selects.filter(select=>bags.indexOf(select)<0)});
    } else {
      selects = [...selects, ...bags];
      this.props.navigation.setParams({selects: selects.filter((bag, index)=>selects.indexOf(bag)===index)});
    }
  }
  onSideMenuChange = (isOpen) => this.setState({isOpen})
  onOpenMenu = () => this.setState({isOpen: true})
  onSelectFactory = (selectFactory) => {
    this.setState({isOpen: false});
    this.props.navigation.setParams({selectFactory});
  }
  handleBarCodeRead = (data) => {
    const selects = (this.props.navigation.state.params&&this.props.navigation.state.params.selects)||[];

    if (data&&data.length===4) {
      const bagNumber = `KK${data}`;
      if (selects.indexOf(bagNumber)>=0) {
        Alert.alert(
          `Bag ${bagNumber} already selected`,
          null,
          [
            {text: 'ok'},
          ],
          { cancelable: true }
        );
      } else {
        const checkingOrders = this.props.checkingOrders;
        const found = checkingOrders&&checkingOrders.find(order=>order.bags&&order.bags.indexOf(bagNumber)>=0);
        if (found) {
          Vibration.vibrate();
          toast(`Bag ${bagNumber} selected`);
          this.props.navigation.setParams({selects: [...selects, bagNumber]});
        } else {
          Alert.alert(
            `Bag ${bagNumber} not found`,
            null,
            [
              {text: 'ok'},
            ],
            { cancelable: true }
          );
        }
      }

      this.setState({inputNumner:''});
    } else {
      this.setState({inputNumner:data});
    }
  }
  render() {
    let { checkingOrders, factories, loading, refetch, navigation } = this.props;
    const { selects, date, selectFactory } = navigation.state.params||{};
    const selectDate = date?moment(date):moment().subtract(1,'days');
    let countMap = {};

    if (checkingOrders) {
      checkingOrders.map(order => {
        const key = order.factoryId||'unassigned';
        if (order.bags) {
          if (countMap[key]) {
            countMap[key] += order.bags.length;
          } else {
            countMap[key] = order.bags.length;
          }
        }
      })
      checkingOrders = checkingOrders.filter(bag=>{
        return (selectFactory?(bag.factoryId===selectFactory.id):!bag.factoryId)||(selects&&bag.bags&&bag.bags.find(bag=>selects.indexOf(bag)>=0));
      });
    }

    let allBags = 0;
    checkingOrders&&checkingOrders.map(order => {
      if (order.bags) {
        allBags += order.bags.length;
      }
    });

    return (
      <SideMenu isOpen={this.state.isOpen} onChange={this.onSideMenuChange}
        menu={
          <ScrollView>
            <Calendar hideExtraDays selected={[selectDate.format('YYYY-MM-DD')]} theme={{
              selectedDayBackgroundColor: primaryColor,
              todayTextColor: primaryColor,
              dotColor: primaryColor,
              arrowColor: primaryColor,}}
              onDayPress={this.onSelectDate} displayLoadingIndicator={loading}/>
              <Text style={styles.header}>Laundry Bag Assignment</Text>
              <List containerStyle={styles.list}>
                <ListItem title='Unassigned' rightIcon={{name:!selectFactory?'radio-button-checked':'radio-button-unchecked',color:!selectFactory?primaryColor:undefined}}
                  subtitle={countMap['unassigned']&&`${countMap['unassigned']} bags`} onPress={()=>this.onSelectFactory(null)}/>
                {factories&&factories.sort((a, b) => {
                  return (countMap[b.id]||0) - (countMap[a.id]||0);
                }).map((factory, index) => {
                  return <ListItem key={index} title={factory.name} subtitle={countMap[factory.id]&&`${countMap[factory.id]} bags`} onPress={()=>this.onSelectFactory(factory)}
                    rightIcon={{name:(selectFactory&&selectFactory.id===factory.id)?'radio-button-checked':'radio-button-unchecked',color:(selectFactory&&selectFactory.id===factory.id)?primaryColor:undefined}}/>;
                })}
              </List>
          </ScrollView>
        }>
        <View style={styles.container}>
          <View style={styles.row}>
            <Button title={selectDate.format('Do')} backgroundColor='transparent' color={primaryColor}
              onPress={this.onOpenMenu}/>
            <View style={styles.container}>
              <SearchBar lightTheme keyboardType='numeric' value={this.state.inputNumner}
                onChangeText={this.handleBarCodeRead} inputStyle={{height:50}} placeholder='KK...'/>
            </View>
            <Button title={`${selects?selects.length:0} / ${allBags}`} backgroundColor='transparent' color={primaryColor}/>
          </View>
          {loading?<Loader/>:
            <RefreshScrollView refetch={refetch}>
              <List containerStyle={styles.list}>
                {checkingOrders&&checkingOrders.map(({orderId, express, business, orderStatus, displayType, orderNumber, bags, checkedBags, assignedFactory, ready}, index) => {
                  const select = bags&&selects&&bags.find(bag=>selects.indexOf(bag)>=0);

                  return <ListItem key={index} title={`${bags?bags.join('; '):'BAG MISSING'} [${assignedFactory||'unassigned'}]`} titleStyle={bags?undefined:styles.bagNotFound}
                    subtitle={`${express?'[Express] ':''}${business?' <BUSINESS>':''}${displayType} #${orderNumber}`} subtitleStyle={business?styles.business:(express?styles.checked:undefined)} hideChevron={bags?false:true}
                    rightIcon={bags?{name:select?'check-box':'check-box-outline-blank',color:select?primaryColor:undefined}:undefined} onPress={() => this.onSelectBag(bags)}/>;
                })}
              </List>
            </RefreshScrollView>
          }
        </View>
      </SideMenu>
    );
  }
}

export default graphql(AssignFactoryQuery, {
  options: ({navigation:{state:{params}}}) => {
    return {
      variables: {
        date: (params&&params.date)||moment([moment().year(), moment().month(), moment().date()]).subtract(1,'days').toDate().toString()
      }
    };
  },
  props: ({data:{checkingOrders, factories, refetch, loading}}) => {
    return {
      checkingOrders,
      factories: factories&&factories.map(factory=>factory),
      loading,
      refetch
    };
  }
})(AssignFactoryPage);

